/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sun.courier.view;

import com.sun.courier.DemoProperties;
import com.sun.courier.dal.DepartmentDAL;
import com.sun.courier.entity.Department;
import com.sun.courier.model.ButtonsPanel;
import com.sun.courier.model.ButtonsRenderer;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Vector;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;

/**
 *
 * @author NamBH
 */
@DemoProperties(
        value = "Department",
        category = "Department Management",
        description = "Magage Department Information, Including: Insert, Update and Delete",
        sourceFiles = { //                "com/sun/courier/view/DepartmentManagement.java",
//                "com/sun/courier/icons/Department.gif"
})
public class DepartmentManagement extends javax.swing.JPanel {

    /**
     * Creates new form DepartmentManagements
     */
    private DepartmentDAL dalDep = new DepartmentDAL();
    private ArrayList<Department> lstDep;
    public DepartmentManagement() {
        initComponents();
        lstDep = dalDep.getAll();
        loadTable();
    }
private void loadTable() {
        Vector cols = new Vector();
        cols.add("No");
        cols.add("Subject Name");
        cols.add("Balance");
        cols.add("Action");

        Vector data = new Vector();
        int i = 1;
        for (Department item : lstDep) {
            Vector row = new Vector();
            row.add(i++);
            row.add(item.getDepartmentName());
            row.add(item.getDescription());
            row.add("");
            data.add(row);
        }

        DefaultTableModel tblModel = new DefaultTableModel(data, cols);
        tblItem.setModel(tblModel);
        
        tblItem.setRowHeight(30);
        
        tblItem.getColumnModel().getColumn(3).setCellRenderer(new ButtonsRenderer());
        tblItem.getColumnModel().getColumn(3).setCellEditor(new ActionButton());
    }
   // <editor-fold defaultstate="collapsed" desc="Action">
    class ActionButton extends ButtonsPanel implements TableCellEditor {

        transient protected ChangeEvent changeEvent = null;

        public ActionButton() {
            super();

            //---->
            //DEBUG: view button click -> control key down + edit button(same cell) press -> remain selection color
            MouseListener ml = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    ButtonModel m = ((JButton) e.getSource()).getModel();
                    if (m.isPressed() && tblItem.isRowSelected(tblItem.getEditingRow()) && e.isControlDown()) {
                        setBackground(tblItem.getBackground());
                    }
                }
            };
            buttons.get(0).addMouseListener(ml);
            buttons.get(0).addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    btnDeleteActionPerformed(ae);
                }
            });
            buttons.get(1).addMouseListener(ml);
            buttons.get(1).addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    btnEditActionPerformed(ae);
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            this.setBackground(table.getSelectionBackground());
            return this;
        }

        @Override
        public Object getCellEditorValue() {
            return "";
        }

        //Copid from AbstractCellEditor
        //protected EventListenerList listenerList = new EventListenerList();
        //transient protected ChangeEvent changeEvent = null;
        @Override
        public boolean isCellEditable(EventObject e) {
            return true;
        }

        @Override
        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        }

        @Override
        public boolean stopCellEditing() {
            fireEditingStopped();
            return true;
        }

        @Override
        public void cancelCellEditing() {
            fireEditingCanceled();
        }

        @Override
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);
        }

        @Override
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
        }

        public CellEditorListener[] getCellEditorListeners() {
            return listenerList.getListeners(CellEditorListener.class);
        }

        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    // Lazily create the event:
                    if (changeEvent == null) {
                        changeEvent = new ChangeEvent(this);
                    }
                    ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent);
                }
            }
        }

        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    // Lazily create the event:
                    if (changeEvent == null) {
                        changeEvent = new ChangeEvent(this);
                    }
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
                }
            }
        }
    }// </editor-fold>
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblItem = new javax.swing.JTable();
        txtName = new javax.swing.JTextField();
        txtDescription = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cbxRole = new javax.swing.JComboBox();
        btnAdd = new javax.swing.JButton();
        lblMessage = new javax.swing.JLabel();

        tblItem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblItem.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblItemMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblItem);

        txtName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNameActionPerformed(evt);
            }
        });

        jLabel1.setText("DepartMent Name:");

        jLabel2.setText("Description:");

        jLabel3.setText("Role:");

        cbxRole.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Receiving-Returning", "DespatChing", "Store", "Administrator" }));

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        lblMessage.setForeground(new java.awt.Color(255, 0, 0));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(27, 27, 27)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cbxRole, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lblMessage)))
                        .addGap(0, 21, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(cbxRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblMessage)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 413, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // -- Dialog
       class Dialog extends JDialog {

        public Dialog() {
            initComponents();
        }
 @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        DeparmentNameDL = new javax.swing.JTextField();
        DescriptionDL = new javax.swing.JTextField();
        cbxRoleDL = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        btUpdate = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();

        jTextField1.setText("jTextField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Depatment Name:");

        jLabel2.setText("Description:");

        cbxRoleDL.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Receiving-Returning", "DespatChing", "Store", "Administrator" }));

        jLabel3.setText("Role:");

        btUpdate.setText("Update");
        btUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btUpdateActionPerformed(evt);
            }
        });

        btCancel.setText("Cancel");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbxRoleDL, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(DeparmentNameDL, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
                                .addComponent(DescriptionDL, javax.swing.GroupLayout.Alignment.LEADING))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(95, 95, 95)
                        .addComponent(btUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(btCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(41, 41, 41)))
                .addGap(34, 34, 34))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(DeparmentNameDL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(DescriptionDL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbxRoleDL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btUpdate)
                    .addComponent(btCancel))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        this.setVisible(false);
    }                                        

    private void btUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        lblMessage.setText("");
            int row = tblItem.getSelectedRow();
            if (row >= 0) {
                Department department = lstDep.get(row);
                //getdata
                String name = DeparmentNameDL.getText();
                String description = DescriptionDL.getText();
                int cbxDL = cbxRoleDL.getSelectedIndex();

                //validate
                boolean check = true;
                String message = "";
                if (name.isEmpty()) {
                    check = false;
                    message = "Name is required!";
                }

                //process
                if (check) {
                    department.setDepartmentName(name);
                    department.setDescription(description);
                    switch (cbxDL) {
                        case 0:
                            cbxDL = 1;
                            break;
                        case 1:
                            cbxDL = 2;
                            break;
                        case 2:
                            cbxDL = 3;
                            break;
                        case 3:
                            cbxDL = 4;
                            break;
                    }
                    department.setRole(cbxDL);
                    check &= dalDep.edit(department);

                    if (check) {
                        JOptionPane.showMessageDialog(null, "Edit department successful");
                        lstDep = dalDep.getAll();
                        loadTable();
                        this.setVisible(false);
                    } else {
                        JOptionPane.showMessageDialog(null, "Edit department fail");
                    }
                } else {
                    lblMessage.setText(message);
                }
            } else {
                JOptionPane.showMessageDialog(null, "You must seleted a department");
            }
        }
    }                                        
    
    
    
    // -- End Dialog
    
    
    // -- botton Acction
    private void btnEditActionPerformed(ActionEvent evt) {
        Dimension ad = new Dimension(300, 170);
        Dialog dialog = new Dialog();
        int row = tblItem.getSelectedRow();
        if (row >= 0) {
            dialog.setLocation(500, 200);
            dialog.setMaximumSize(ad);
            dialog.setMinimumSize(ad);
            dialog.setVisible(true);
            Department dep = lstDep.get(row);
            DeparmentNameDL.setText(dep.getDepartmentName());
            DescriptionDL.setText(dep.getDescription());
            cbxRoleDL.setSelectedIndex(dep.getRole()-1);
        }
    }

    private void btnDeleteActionPerformed(ActionEvent evt) {
        int row = tblItem.getSelectedRow();
        if (row >= 0) {
            int confirm = JOptionPane.showConfirmDialog(null, "Are you sure delete this?", "Delete", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                boolean check = dalDep.delete(lstDep.get(row).getDepId());

                if (check) {
                    JOptionPane.showMessageDialog(null, "Delete department successful");

                    lstDep = dalDep.getAll();
                    loadTable();
                } else {
                    JOptionPane.showMessageDialog(null, "Department have Employee. Delete fail.!");
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "You must seleted a department");
        }
    }

    
    // -- END button Acction
    
    private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNameActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        lblMessage.setText("");

        //getdata
        String name = txtName.getText();
        String description = txtDescription.getText();
        int cbx = cbxRole.getSelectedIndex();
        //validate
        boolean check = true;
        String message = "";
        if (name.isEmpty()) {
            check = false;
            message = "Name is required!";
        }

        //process
        if (check) {
            switch(cbx){
                case 0: cbx = 1;
                    break;
                case 1: cbx = 2;
                    break;
                case 2: cbx = 3;
                    break;
                case 3: cbx = 4;
                    break;               
            }
            check &= dalDep.add(new Department(0, name, description,cbx));

            if (check) {
                JOptionPane.showMessageDialog(null, "Add department successful");

                lstDep = dalDep.getAll();
                loadTable();
            } else {
                JOptionPane.showMessageDialog(null, "Add department fail");
            }
        } else {
            lblMessage.setText(message);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void tblItemMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblItemMouseClicked
        // TODO add your handling code here:
         int row = tblItem.getSelectedRow();
        if (row >= 0) {
            Department dep = lstDep.get(row);
            txtName.setText(dep.getDepartmentName());
            txtDescription.setText(dep.getDescription());
            
        }
    }//GEN-LAST:event_tblItemMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JComboBox cbxRole;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMessage;
    private javax.swing.JTable tblItem;
    private javax.swing.JTextField txtDescription;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
    private javax.swing.JTextField DeparmentNameDL;
    private javax.swing.JTextField DescriptionDL;
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btUpdate;
    private javax.swing.JComboBox cbxRoleDL;
    private javax.swing.JLabel jLabel1DL;
    private javax.swing.JLabel jLabel2DL;
    private javax.swing.JLabel jLabel3DL;
    private javax.swing.JTextField jTextField1;

}
